package pikasial.graphique;

import java.awt.Component;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.Collection;
import java.util.Comparator;
import java.util.Observable;
import java.util.Observer;
import java.util.SortedSet;
import java.util.TreeSet;

import javax.swing.AbstractListModel;
import javax.swing.DefaultListCellRenderer;
import javax.swing.ImageIcon;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JMenuItem;
import javax.swing.JPopupMenu;
import javax.swing.JScrollPane;
import javax.swing.ListSelectionModel;
import javax.swing.SwingConstants;
import pikasial.images.AlbumPhotos;
import pikasial.images.ListeAlbums;
import pikasial.images.PikImage;

/**
 * Cette classe représente la vue de la liste d'albums.
 * @author ESIAL - Groupe 14
 */
@SuppressWarnings("serial")
public final class NavigateurAlbums extends JScrollPane implements java.util.Observer {

    /** Vue de la liste d'album */
    private JList liste;
    private AlbumsListModel alm;
    private JPopupMenu popup;
    private JMenuItem paste;

    /**
     * Crée une instance du navigateur d'albums.
     */
    NavigateurAlbums() {
    	alm = new AlbumsListModel(ListeAlbums.getInstance().getAllAlbums());
        liste = new JList();
        liste.setModel(alm);
        liste.setCellRenderer(new ListeAlbumsRenderer());
        liste.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        ListeAlbums.getInstance().addObserver(this);
        ListSelectionModel selMod = liste.getSelectionModel();

        selMod.addListSelectionListener(new javax.swing.event.ListSelectionListener() {

            public void valueChanged(javax.swing.event.ListSelectionEvent e) {
                if (e.getValueIsAdjusting() == false && liste.getSelectedIndex() != -1
                		&& liste.getSelectedValue() != ListeAlbums.getInstance().getAlbumAffiche()) {
                        ListeAlbums.getInstance().setAlbumAffiche((AlbumPhotos) liste.getSelectedValue());
                }
            }
        });
//        liste.addMouseListener(new MouseListener() {
//
//			public void mouseClicked(MouseEvent e) {
//				if (e.getButton() == MouseEvent.BUTTON1) {
//					int index = liste.locationToIndex(e.getPoint());
//                    if (index != -1) {
//                    	AlbumPhotos ap = (AlbumPhotos) liste.getModel().getElementAt(index);
//                    	ListeAlbums.getInstance().setAlbumAffiche(ap);
//                    }
//                }
//			}
        popup = new JPopupMenu();
        JMenuItem suppr = new JMenuItem("Supprimer l'album");
        suppr.setIcon(new ImageIcon(getClass().getResource(pikasial.utils.PikasialConstantes.REMOVE_16_ICON_PATH)));
        suppr.addActionListener(new ActionListener() {
        	public void actionPerformed(ActionEvent ae) {
        		if (!liste.isSelectionEmpty()) {
        			ListeAlbums.getInstance().supprimerAlbum(liste.getSelectedIndex());
        		}
        	}
        });
        paste = new JMenuItem("Coller dans");
        paste.setIcon(new ImageIcon(getClass().getResource(pikasial.utils.PikasialConstantes.PASTE_16_ICON_PATH)));
        paste.addActionListener(new ActionListener() {
        	public void actionPerformed(ActionEvent ae) {
        		if (!liste.isSelectionEmpty() && !PressePapier.getInstance().isEmpty()) {
        			AlbumPhotos ap = (AlbumPhotos) liste.getSelectedValue();
        			PikImage[] piks = PressePapier.getInstance().coller();
        			for (PikImage pik : piks)
        				ap.addImage(pik);
        		}
        	}
        });
        popup.add(suppr);
        popup.addSeparator();
        popup.add(paste);

        liste.addMouseListener(new MouseAdapter() {
        	public void mouseReleased(MouseEvent me) {
        		if (me.getButton() == MouseEvent.BUTTON3 && !liste.isSelectionEmpty()) {
        			paste.setEnabled(!PressePapier.getInstance().isEmpty());
        			popup.show(me.getComponent(),me.getX(),me.getY());
        		}
        	}
        });
        setViewportView(liste);
    }

    public AlbumPhotos getAlbumAt(int index) {
    	return (AlbumPhotos) alm.getElementAt(index);
    }

    public int getIndexOf(AlbumPhotos ap) {
    	return alm.indexOf(ap);
    }

//    /**
//     * Retourne la vue de la liste d'albums.
//     * @return la vue de la liste
//     */
//    JList getList() {
//        return liste;
//    }

    public void setSelectedIndex(int index) {
    	liste.setSelectedIndex(index);
    }

    public void clearSelection() { liste.clearSelection(); }

    public int getSelectedIndex() { return liste.getSelectedIndex(); }

    public AlbumPhotos getSelectedAlbum() { return (AlbumPhotos) liste.getSelectedValue(); }

	public void update(Observable o, Object arg) {
		liste.repaint();
	}


    class AlbumsListModel extends AbstractListModel implements Observer {

    	public final Comparator<AlbumPhotos> COMP_ALBUMS =
    		new Comparator<AlbumPhotos>() {
				public int compare(AlbumPhotos arg0, AlbumPhotos arg1) {
					return arg0.getName().compareTo(arg1.getName());
				}
    	};

        private SortedSet<AlbumPhotos> albums;

        AlbumsListModel(Collection<AlbumPhotos> albums) {
            super();
            this.albums = new TreeSet<AlbumPhotos>(COMP_ALBUMS);
            this.albums.addAll(albums);
            ListeAlbums.getInstance().addObserver(this);
        }

        public Object getElementAt(int index) {
            int i=0;
            AlbumPhotos alb = null;
            for (AlbumPhotos ap : albums) {
            	if (i++ == index) {
            		alb = ap;
            		break;
            	}
            }
            return alb;
        }

        public int indexOf(AlbumPhotos ap) {
        	int i = 0;
        	boolean trouve = false;
        	for (AlbumPhotos alb : albums) {
        		if (alb == ap) {
        			trouve = true;
        			break;
        		}
        		i++;
        	}
        	return (trouve)?i:-1;
        }

        public int getSize() {
            return albums.size();
        }

        public void update(Observable o, Object arg) {
        	if (arg.equals(ListeAlbums.NOTIF_ALBUM)) {
        		albums.clear();
        		albums.addAll(ListeAlbums.getInstance().getAllAlbums());
        		fireContentsChanged(this,0,albums.size()-1);
        	}
        }
    }


    /**
     * Le décorateur de la liste d'album.
     * @author ESIAL - Groupe 14
     */
    @SuppressWarnings("serial")
    final class ListeAlbumsRenderer extends DefaultListCellRenderer {

        @Override
        public Component getListCellRendererComponent(final JList list,
            final Object value,
            final int index,
            final boolean isSelected,
            final boolean cellHasFocus) {

            /* On utilise le comportement par defaut, que l'on va modifier */
            Component c = super.getListCellRendererComponent(list, value,
                index, isSelected, cellHasFocus);

            ImageIcon icon = new ImageIcon(getClass().getResource("/img/gnome-graphics.png"));
            JLabel lab = (JLabel) c;
            AlbumPhotos album = (AlbumPhotos) value;
            lab.setIcon(icon);

            String text = album.getName()+" ("+album.getImageCount() + ")";

            lab.setFont(new Font(null, Font.BOLD, 12));
            lab.setVerticalTextPosition(SwingConstants.CENTER);

            lab.setIconTextGap(10);
            lab.setText(text);

            return c;
        }
    }


}
